import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/pctask/PcrwViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';
import 'package:flutter_ahj_app/base/widget/NoneData.dart';

enum PcTaskPageType { dwcl, wfq }

class PCTask_list_view extends BaseStatefulWidget {
  final PcTaskPageType pageType;
  PCTask_list_view({this.pageType});

  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return PCTask_list_viewtate();
  }
}

class PCTask_list_viewtate extends BaseState<PcrwViewModel, PCTask_list_view> {
  TextEditingController _controller = TextEditingController(text: '');
  ScrollController _scrollController;

  bool canLoadMore = true;
  List _datalist; //请求的数据列表
  int pageIndex = HttpBaseConst.pageIndex;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (canLoadMore) _getData(1);
      }
    });
    Future.delayed(Duration.zero, () {
      _getData(0);
    });
  }

  @override
  Widget initWidget() {
    return _bodyView();
  }

  _bodyView() {
    return Container(
      color: Color(0xfff6f6f6),
      child: Column(
        children: [
          _searchLayout(),
          Expanded(
            child: _datalist == null
                ? LoadingWidget()
                : _datalist.length == 0
                    ? NoneData()
                    : Container(
                        margin: EdgeInsets.fromLTRB(
                            Dimens.dimens16, 0, Dimens.dimens16, Dimens.dimens16),
                        child: RefreshIndicator(
                          onRefresh: () => _getData(0),
                          child: ListView.builder(
                              shrinkWrap: true,
                              physics: AlwaysScrollableScrollPhysics(),
                              itemCount: _datalist.length,
                              controller: _scrollController,
                              itemBuilder: (context, index) {
                                return _itemContentView(index);
                              }),
                        ),
                      ),
          ),
          _bottomBtnView()
        ],
      ),
    );
  }

  _getPerson(List list) {
    // 按逗号拼接
    String ids = '';
    for (var i = 0; i < list.length; i++) {
      String string = '';
      if (ids.length > 0) {
        string = '、';
      }
      ids = ids + string + list[i];
    }
    return ids;
  }

  _itemContentView(int index) {
    return Container(
      child: Column(
        children: [
          Container(
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              decoration: BoxDecoration(
                color: SQColor.white,
                borderRadius: BorderRadius.circular(6),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          Image.asset("img/pxrw_zt_d.png",
                              width: 55,
                              height: Dimens.dimens20,
                              fit: BoxFit.fill),
                          JText(
                            StringUtils.getStr(
                                _datalist[index]["taskStatusName"]),
                            color: SQColor.white,
                            fontSize: Dimens.dimens12,
                          ),
                        ],
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText(
                      StringUtils.getStr(_datalist[index]["taskName"]),
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText(
                      '任务时间:  ${StringUtils.getStr(_datalist[index]["startTime"])} ~ ${StringUtils.getStr(_datalist[index]["endTime"])}',
                      color: StringUtils.getStr(_datalist[index]["overdueFlag"].toString()) == "1" ? SQColor.red : SQColor.black_999999,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText(
                      '执行人：${_getPerson(_datalist[index]["inspectorOpenNameList"])}',
                      color: SQColor.black_999999,
                    ),
                  ),
                  widget.pageType == PcTaskPageType.wfq ? Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText(
                      '完成时间：${_datalist[index]["taskCompleteTime"] ?? ''}',
                      color: SQColor.black_999999,
                    ),
                  ) : Container(),
                  SizedBox(
                    height: Dimens.dimens16,
                  ),
                  _bottomView(index),
                  SizedBox(
                    height: Dimens.dimens16,
                  ),
                ],
              )),
          Container(
            height: 10,
            color: Color(0xfff6f6f6),
            width: double.infinity,
          ),
        ],
      ),
    );
  }

  _bottomBtnView() {
    return InkWell(
      onTap: () {
        Navigator.pushNamed(context, '/CreateRWView', arguments: {});
      },
      child: SafeArea(
        child: Container(
          margin: EdgeInsets.only(left: 15, right: 15),
          height: 45,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: SQColor.blue_026FFF,
            borderRadius: BorderRadius.circular(10),
          ),
          child: JText('创建任务', color: Colors.white),
        ),
      ),
    );
  }

  _bottomView(int index) {
    return widget.pageType == PcTaskPageType.dwcl
        ? _ywc(index)
        : _ywcwfq(index);
  }

  _ywc(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('开始排查', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('开始排查', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _ywcwfq(int index) {
    return Container(
      padding: EdgeInsets.only(left: 5),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('查看详情', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: SQColor.white,
                    border: Border.all(
                      color: Color(0xff165DFF),
                    ),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('查看详情', color: Color(0xff165DFF)),
              ),
            ),
          ),
          Expanded(
            child: InkWell(
              onTap: () {
                _yhitemClick('复制', index);
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(right: 5),
                width: 88,
                height: 35,
                decoration: BoxDecoration(
                    color: Color(0xff165DFF),
                    borderRadius: BorderRadius.circular(16)),
                child: JText('复制', color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _yhitemClick(String title, int index) {
    switch (title) {
      case '查看详情':
        Navigator.pushNamed(context, '/PCrwDetailView',
            arguments: _datalist[index]["id"].toString());
        break;
      case '开始排查':
        DateTime ksTime = DateTime.parse(_datalist[index]['startTime']);
        if (ksTime.isAfter(DateTime.now())) {
          ToastUtils.showToast('当前任务未到开始时间');
        } else {
          Navigator.pushNamed(context, '/PCrwStartView',
            arguments: _datalist[index]["id"].toString()).then((value) {
            _datalist.clear();
            _getData(0);
          });
        }        
        break;
      case '复制':
        Navigator.pushNamed(context, '/CreateRWView',
                arguments: _datalist[index])
            .then((value) {
          _datalist.clear();
          _getData(0);
        });
        break;
      default:
    }
  }

  _searchLayout() {
    return Container(
      margin: EdgeInsets.all(Dimens.dimens16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.0),
      ),
      child: Row(
        children: [
          Container(
            width: 20,
            height: 20,
            margin: EdgeInsets.only(left: 10),
            child: Icon(
              Icons.search,
              color: Color(0xffaaaaaa),
            ),
          ),
          Expanded(
            child: Container(
              height: Dimens.dimens36,
              child: TextField(
                controller: _controller,
                maxLines: 1,
                onSubmitted: (value) {
                  _getData(0);
                },
                decoration: InputDecoration(
                  hintText: "输入名称搜索",
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  fillColor: Colors.white,
                  //filled = true 时为背景颜色
                  filled: true,
                  contentPadding: EdgeInsets.fromLTRB(
                      Dimens.dimens16, 0, Dimens.dimens16, 0),
                  enabledBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  suffixIcon: _controller.text.length > 0
                      ? new IconButton(
                          icon: Icon(
                            Icons.close,
                            color: SQColor.per38Black,
                            size: Dimens.dimens20,
                          ),
                          onPressed: () {
                            setState(() {
                              _controller.clear();
                              _getData(0);
                            });
                          })
                      : null,
                ),
              ),
            ),
          ),
          Container(
            width: 1,
            color: SQColor.black_BDBDBD,
            height: Dimens.dimens16,
            margin: EdgeInsets.only(right: Dimens.dimens16),
          ),
          GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              _getData(0);
            },
            child: Container(
              padding: EdgeInsets.only(right: Dimens.dimens16),
              height: Dimens.dimens48,
              alignment: Alignment.centerRight,
              child: Text("搜索",
                  style: TextStyle(
                      color: Color(0xff165DFF), fontSize: Dimens.textSize28)),
            ),
          ),
        ],
      ),
    );
  }

  ///获得数据
  _getData(int type) async {
    if (type == 0) {
      //刷新
      pageIndex = HttpBaseConst.pageIndex;
    } else {
      //加载更多
      pageIndex += 1;
    }

    print(_controller.text);
    var map = {
      'size': HttpBaseConst.pageSize,
      'current': pageIndex,
      'taskName': _controller.text,
      'taskQueryType':
          widget.pageType == PcTaskPageType.dwcl ? 'waitHandle' : 'launched'
    };

    viewModel.getPcrwList(map);
    viewModel.getPcrwListStream().listen((result) {
      print(result);
      if (result['code'] == "0") {
        if (_datalist == null) _datalist = List();
        if (result == null ||
            result['data'] == null ||
            result['data']['total'] == 0 ||
            result['data']['records'] == null ||
            result['data']['records'].length == 0) {
          setState(() {
            if (type == 0) {
              //刷新
              _datalist.clear();
            } else {
              //加载更多
            }
          });
        } else {
          setState(() {
            if (type == 0) {
              //刷新
              _datalist.clear();
            } else {
              //加载更多
            }
            _datalist.addAll(result['data']['records']);
          });
        }
        setState(() {
          canLoadMore =
              _datalist.length == result['data']['total'] ? false : true;
        });
        print("******************length = ${_datalist.length}");
      } else {
        setState(() {
          _datalist = List();
        });
        ToastUtils.showToast(result['msg']);
      }
    });
  }
}
